﻿#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Antlr.Runtime;
using EditeurSyntaxiqueVocal.Class;
using EditeurSyntaxiqueVocal.Controls;
using EditeurSyntaxiqueVocal.Forms.CommunicationsForm;
using EditeurSyntaxiqueVocal.Intellisencs;
using EditeurSyntaxiqueVocal.Languages.LanguageZ.Grammaire.output;
using EditeurSyntaxiqueVocal.Languages.LanguageZ;
using EditeurSyntaxiqueVocal.Languages.LanguageZ.NewFolder;
using EditeurSyntaxiqueVocal.LesOnglets;
using EditeurSyntaxiqueVocal.Properties;
using EditeurSyntaxiqueVocal.RechercherEtRemplacer;
using EditeurSyntaxiqueVocal.Dump;
using EditeurSyntaxiqueVocal.ConversionZFrEntreEnu;
using TextEditor;
using TextEditor.Actions;
using System.Threading;
using System.Diagnostics;
using TextEditor.Document;
using Timer = System.Threading.Timer;

#endregion

namespace EditeurSyntaxiqueVocal.Forms
{
    /// <summary>
    /// La classe prancipale de l'application MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        public string[] nomFiles;
        private readonly StartForm startForm;
        private PageStart2 formS;

        #region -- Vars --

        /// <summary>
        /// 
        /// </summary>
        public static Langages _LangageActive;

        /// <summary>
        /// Collection contient les onglet de l'application.
        /// </summary>
        private static OngletsCollection _ongletsCollection;

        /// <summary>
        /// Utilisre pour savegarder le chemain de repértoire de démarage de l'application.
        /// </summary>
        public static string appPath;

        /// <summary>
        /// La form de communication entre la Machine et l'homme.
        /// </summary>       
        public static CommunicationForm CommunicationForm;

        /// <summary>
        /// La form de la recherche et remplacer.
        /// </summary>
        private static RechercherRemplacerForm _rechercherRemplaceForm;


        public static Completion _completion;

        /// <summary>
        /// 
        /// </summary>
        public ConfirmationFrom ConfirmationEnregistrement;

        /// <summary>
        /// 
        /// </summary>
        private ListeVariables listeVariables;

        // private bool Libre = true;
        //private List<string[]> listMotCleZFrEnu = new List<string[]>();

        private Random r3 = new Random();

        public static StartPageOnglet StartPageOnglet;

        private OngletActions _ongletActions;

        private OutilsPara _outilsPara;

        #endregion

        #region -- Constructeurs --

        ///<summary>
        /// Construncteur
        ///</summary>
        public MainForm()
        {
            // this.Visible = false;
            InitializeComponent();

            appPath = Application.StartupPath + @"\";

            InitBars();
            InitEditeurSyntaxiqueVocal();

            //barIndexExplorerSolution.Ico = Resources.VSProject_genericproject;
            _ongletsCollection = new OngletsCollection(tabControl1);

            //MainForm_Load(null, null);

            listeVariables = new ListeVariables("", variablesList.treeViewVariableListe);

            #region Init Controls

            // 
            // StartPageOnglet
            // 
            StartPageOnglet = new StartPageOnglet();
            this.tabPage1.Controls.Add(StartPageOnglet);
            StartPageOnglet.Dock = DockStyle.Fill;
            StartPageOnglet.Location = new Point(0, 0);
            StartPageOnglet.Name = "StartPageOnglet";
            StartPageOnglet.Size = new Size(1022, 336);
            StartPageOnglet.TabIndex = 0;
            StartPageOnglet.New += ribbonButtonNewFile_Click;
            StartPageOnglet.Open += ribbonButtonOpenFile_Click;
            StartPageOnglet.OnRecentFileLinkCliked += StartPageOnglet_OnRecentFileLinkCliked;
            // 
            // label6
            // 
            label6 = new System.Windows.Forms.Label();
            panelBas.Controls.Add(label6);
            label6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            label6.AutoSize = true;
            label6.BackColor = System.Drawing.Color.WhiteSmoke;
            label6.Location = new System.Drawing.Point(1029, 397);
            label6.Name = "label6";
            label6.Size = new System.Drawing.Size(19, 13);
            label6.TabIndex = 8;
            label6.Text = "    ";
            // 
            // label5
            // 
            label5 = new System.Windows.Forms.Label();
            panelBas.Controls.Add(label5);
            label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            label5.AutoSize = true;
            label5.BackColor = System.Drawing.Color.WhiteSmoke;
            label5.Location = new System.Drawing.Point(921, 398);
            label5.Name = "label5";
            label5.Size = new System.Drawing.Size(19, 13);
            label5.TabIndex = 7;
            label5.Text = "    ";

            #endregion
        }

        public MainForm(PageStart2 formS)
            : this()
        {
            this.formS = formS;
        }

        public MainForm(StartForm startForm)
            : this()
        {
            this.startForm = startForm;
        }

        private System.Windows.Forms.Timer timer;

        /// <summary>
        /// Utiliser cette constructeur pour une command ligne.
        /// </summary>
        /// <param name="NomFiles">Le nom de fichier qui va être lu.</param>
        public MainForm(string[] NomFiles)
            : this()
        {
            try
            {
                nomFiles = NomFiles;
                timer = new System.Windows.Forms.Timer();
                timer.Interval = 1000;
                timer.Enabled = true;
                timer.Start();
                timer.Tick += timer_Tick;
            }
            catch (Exception ex)
            {

            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                AddArgs(nomFiles);
                if (timer != null) timer.Stop();
            }
            catch (Exception ex)
            {
            }
        }

        public void AddArgs(string[] nomsFiles)
        {
            foreach (string nomFile in nomsFiles)
                try
                {
                    new OngletActions(OngletsCollection).Ouvrir(nomFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Erreur");
                }
            if (OngletsCollection.Count == 0)
            {
            }
        }

        #endregion

        #region -- Properieter --

        public OngletActions OngletActions
        {
            get { return _ongletActions; }
            set { _ongletActions = value; }
        }

        /// <summary>
        /// La form de la recherche et remplacer.
        /// </summary>
        public static RechercherRemplacerForm RechercherRemplaceForm
        {
            get { return _rechercherRemplaceForm; }
            set { _rechercherRemplaceForm = value; }
        }

        /// <summary>
        /// L'editeur de text pracipale, touts les travailles sur cette editeur.
        /// </summary>
        public static Onglet OngletActive
        {
            get { return OngletsCollection.OngletActive; }
            set
            {
                if (OngletsCollection.OngletActive != null)
                    OngletsCollection.OngletActive = value;
            }
        }

        ///<summary>
        /// Le TextArea de document Active.
        ///</summary>
        public static TextArea TextAreaOngletActive
        {
            get
            {
                return OngletActive != null ? OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea : null;
            }
        }

        ///<summary>
        /// Le TextArea de document Active.
        ///</summary>
        public static IDocument DocumentOngletActive
        {
            get
            {
                return OngletActive != null ? OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document : null;
            }
        }

        /// <summary>
        /// Collection contient les onglet de l'application.
        /// </summary>
        public static OngletsCollection OngletsCollection
        {
            get { return _ongletsCollection; }
        }

        /// <summary>
        /// 
        /// </summary>
        public static Langages LangageActive
        {
            get { return _LangageActive; }
            set { _LangageActive = value; }
        }

        public static Completion Completion
        {
            get
            {
                return _completion;
            }
            set
            {
                _completion = value;
            }
        }

        public OutilsPara OutilsPara
        {
            get { return _outilsPara; }
            set { _outilsPara = value; }
        }

        public Ribbon RibbonMenu
        {
            get { return ribbonMenu; }
        }

        #endregion

        #region Actions Button

        /// <summary>
        /// Execute un'action Annuler (Undo) sur le document active.
        /// </summary>
        private void toolStripButtonUndo_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                OngletActive.EditeurTextOnglet.Undo();
        }

        /// <summary>
        /// Execute un'action Rétablir (Redo) sur le document active.
        /// </summary>
        private void toolStripButtonRebdo_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                OngletActive.EditeurTextOnglet.Redo();
        }

        /// <summary>
        /// déplace le Cursor vers la fin du document
        /// </summary>
        public static void MoveToEnd()
        {
            if (OngletActive != null)
                new MoveToEnd().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers la fin d ela linge.
        /// </summary>
        public static void MoveToEndLine()
        {
            if (OngletActive != null)
                new End().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers le debut de la ligne courant.
        /// </summary>
        public static void MoveToHome()
        {
            if (OngletActive != null)
                new Home().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers le début de la document.
        /// </summary>
        public static void MoveToStart()
        {
            if (OngletActive != null)
                new MoveToStart().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace la page vers la bas.
        /// </summary>
        public static void MovePageDown()
        {
            if (OngletActive != null)
            {
                new ShiftMovePageDown().Execute(TextAreaOngletActive);
                new ClearAllSelections().Execute(TextAreaOngletActive);
            }
        }

        /// <summary>
        /// déplace la page vers la haut.
        /// </summary>
        public static void MovePageUp()
        {
            if (OngletActive != null)
                new MovePageUp().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers la bas.
        /// </summary>
        public static void MoveCaretDown()
        {
            if (OngletActive != null)
                new ShiftCaretDown().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers la haut.
        /// </summary>
        public static void MoveCaretUp()
        {
            if (OngletActive != null)
                new ShiftCaretUp().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers la gauche.
        /// </summary>
        public static void MoveCaretLeft()
        {
            if (OngletActive != null)
                new ShiftCaretLeft().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// déplace le Cursor vers la droite
        /// </summary>
        public static void MoveCaretRigth()
        {
            if (OngletActive != null)
                new ShiftCaretRight().Execute(TextAreaOngletActive);
        }


        /// <summary>
        /// 
        /// </summary>
        public static void ReturnCaret()
        {
            if (OngletActive != null)
                new Return().Execute(TextAreaOngletActive);
        }


        /// <summary>
        /// Enregistre le document active.
        /// </summary>
        private void ribbonButtonSave_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new OngletActions(OngletsCollection).Enregistrer();
        }

        /// <summary>
        /// Enregistre sous le document active.
        /// </summary>
        private void ribbonButtonSaveAs_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new OngletActions(OngletsCollection).EnregistrerSous();
        }

        /// <summary>
        /// Enregistre tout les documents actives.
        /// </summary>
        private void ribbonButtonSaveAll_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new OngletActions(OngletsCollection).EnregistrerTout();
        }

        /// <summary>
        /// Ferme le document active.
        /// </summary>
        private void ribbonButtonClose_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new OngletActions(OngletsCollection).Fermer();
        }

        /// <summary>
        /// Nouveau document.
        /// </summary>
        private void ribbonButtonNewFile_Click(object sender, EventArgs e)
        {
            new OngletActions(OngletsCollection).Nouveau();
            VoixMainForm.InsertMotCle("base program", null, false);
        }

        /// <summary>
        /// Sélectionne le text de document active.
        /// </summary>        
        private void ribbonButtonSelectAll_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new SelectWholeDocument().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// Ferme tout les document ouvert.
        /// </summary>
        private void ribbonButtonCloseAll_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new OngletActions(OngletsCollection).FermerTout(true);
        }

        /// <summary>
        /// Ferme l'application.
        /// </summary>
        private void ribbonButtonExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// Coller le text de document active.
        /// </summary>
        private void ribbonButtonPaste_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new Paste().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// Couper le text sélectionner de document active.
        /// </summary>
        private void ribbonButtonCut_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new Cut().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// Copier le text sélectionner de document active.
        /// </summary>
        private void ribbonButtonCopy_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new Copy().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// Supprime le text Sélectionner de document active.
        /// </summary>
        private void ribbonButtonDelete_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                new Delete().Execute(TextAreaOngletActive);
        }

        /// <summary>
        /// Ouvrir la fenêtre de recherche et remplacer.
        /// </summary>
        private void ribbonButtonFind_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            _rechercherRemplaceForm.Show();
        }

        /// <summary>
        /// Divise le document active en deux partis.
        /// </summary>
        private void ribbonButtonSplit_Click(object sender, EventArgs e)
        {
            if (OngletActive != null)
                OngletActive.EditeurTextOnglet.Split();
        }

        /// <summary>
        /// Ouvrir un fichier exist déjà.
        /// </summary>
        private void ribbonButtonOpenFile_Click(object sender, EventArgs e)
        {
            new OngletActions(OngletsCollection).Ouvrir();
        }

        private void ribbonButton16_Click(object sender, EventArgs e)
        {
            new About().ShowDialog();
        }

        private void ribbonButtonConverterFr_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            new OngletActions(OngletsCollection).Nouveau(Langages.Z2Fr);
            OngletActive.EditeurTextOnglet.SetHighlighting("ZFr");
            OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document.TextContent =
                new ConversionZFrEnu(OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document.TextContent,
                                     TypeConversionZ.Enu, true).Converter();
            OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Invalidate();
        }

        private void ribbonButtonConverterEnu_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            ribbonButtonNewFile_Click(sender, e);
            OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document.TextContent = new ConversionZFrEnu(
                OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document.TextContent,
                TypeConversionZ.Fr, true).Converter().Replace("\r\n\r\n", "\r\n");
            OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Invalidate();
        }

        #endregion

        /// <summary>
        /// Evenement après la céation de cette object (this) s'execute.
        /// </summary>
        public void MainForm_Load(object sender, EventArgs e)
        {
            VoixMainForm.InitialMotCleObjRecoContext();
            voiceOption.VoiceOption_Load(sender, e);
            CommunicationForm = new CommunicationForm(this);
            CommunicationForm.Owner = this;
            CommunicationForm.EtatVoiceChange += cf_EtatVoiceChange;
            CommunicationForm.VoiceAllEnd += cf_VoiceAllEnd;

            _rechercherRemplaceForm = new RechercherRemplacerForm(this);
            OngletsCollection.OngletsCollectionVider += OnOngletsCollectionVider;
            OngletsCollection.OngletActiveChanger += OngletsCollection_OngletActiveChanger;
            OngletsCollection.OnAdd += solutionExplorer.OngletsCollection_OnAdd;
            OngletsCollection.OnRemove += solutionExplorer.OngletsCollection_OnRemove;

            LangageActive = Langages.Z2;
            ThCompParant = new Thread(thp);
            ThCompParant.IsBackground = true;
            ThCompParant.Start();

            formEditorSimple = new FormEditorSimple(this);
            errorList.gridViewCellMouseEventHandler += errorList_gridViewCellMouseEventHandler;

            VoixMainForm.Inden += ribbonButtonIndentation_Click;

            try
            {
                AddArgs(nomFiles);
            }
            catch (Exception)
            {
            }
            listeErrorZ.ListErrorZFrEnu = listeErrorZ.ParserXml();
        }

        /// <summary>
        /// 
        /// </summary>
        private static void Caret_PositionChanged(object sender, EventArgs e)
        {
            label6.Text = OngletActive.EditeurTextOnglet.ActiveTextAreaControl.Caret.Column.ToString();
            label5.Text = string.Format("{0}", OngletActive.EditeurTextOnglet.ActiveTextAreaControl.Caret.Line + 1);
        }

        /// <summary>
        /// 
        /// </summary>
        private void OngletsCollection_OngletActiveChanger(object sender, EventArgs e)
        {
            OngletsCollection.OngletActive.EditeurTextOnglet.ActiveTextAreaControl.Caret.PositionChanged -=
                Caret_PositionChanged;
            OngletsCollection.OngletActive.EditeurTextOnglet.ActiveTextAreaControl.Caret.PositionChanged +=
                Caret_PositionChanged;
            OngletsCollection.OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.KeyUp -=
                TextArea_KeyUp;
            OngletsCollection.OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.KeyUp +=
                TextArea_KeyUp;
            OngletActive.EditeurTextOnglet.ActiveTextAreaControl.TextArea.Document.DocumentChanged +=
                            EditeurTextOnglet_InsertText;

            if (Completion != null)
                Completion.Close();

            Completion = new Completion(OngletActive.EditeurTextOnglet, this);
            Completion.StartPosition = FormStartPosition.Manual;
            Completion.Owner = this;
            ThComp = new Thread(Completion.ThParser);
            Completion.ChangerPositionCursorAndVoice();

            EditeurTextOnglet_InsertText(null, null);
        }

        void TextArea_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Tab:
                    if (e.Shift)
                        VoixMainForm.AppliqueMarker();
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void OnOngletsCollectionVider(object sender, HelpEventArgs hlpevent)
        {
            _rechercherRemplaceForm.Hide();
        }

        /// <summary>
        /// Après cette fenêtre été visible, ouvrir la fenêtre de la CommunicationForm.
        /// </summary>
        private void MainForm_Shown(object sender, EventArgs e)
        {
            CommunicationForm.Show();
        }

        /// <summary>
        /// Cette evenmment lacera à partire de la form CommiunicationForm.
        /// Lance si l'état de la voix est change.
        /// </summary>
        private static void cf_EtatVoiceChange(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        private static void cf_VoiceAllEnd(object sender, EventArgs e)
        {
        }

        private void StartPageOnglet_OnRecentFileLinkCliked(object sender, EventArgs e)
        {
            RecentFileStartPage page = null;

            foreach (object control in StartPageOnglet.RecentFilesGroup.Panel.Controls)
                if (control is RecentFileStartPage)
                    if (((RecentFileStartPage)control).Path == (string)sender)
                    {
                        page = ((RecentFileStartPage)control);
                        if (!File.Exists((string)sender))
                        {
                            StartPageOnglet.RecentFilesGroup.Panel.Controls.Remove(page);
                            EditeurSyntaxiqueVocal.Controls.StartPageOnglet.RecentFiles.Remove(page.Path);
                            return;
                        }
                        break;
                    }

            if (page != null)
                try
                {
                    StartPageOnglet.RecentFilesGroup.Panel.Controls.SetChildIndex(page,
                                                                                  StartPageOnglet.RecentFilesGroup.
                                                                                      Panel.Controls.Count - 1);
                }
                catch
                {
                }

            new OngletActions(OngletsCollection).Ouvrir((string)sender);
            EditeurSyntaxiqueVocal.Controls.StartPageOnglet.RecentFiles.Remove((string)sender);
            ((IList)EditeurSyntaxiqueVocal.Controls.StartPageOnglet.RecentFiles).Add(new TokenRecentFile((string)sender));
        }

        private static Thread ThComp;
        private static Thread ThCompParant;
        public bool bthp = true;
        private void thp()
        {
            while (true)
            {
                if (bthp)
                {
                    bthp = false;
                    if (ThComp != null) ThComp.Abort();
                    if (Completion != null)
                    {
                        ThComp = new Thread(Completion.ThParser);
                        //ThComp.IsBackground = true;
                        ThComp.Start();
                    }
                }
                Thread.Sleep(200);
            }
        }

        public static string str = string.Empty;
        public void EditeurTextOnglet_InsertText(object sender, EventArgs e)
        {
            if (Completion != null)
                if (!Completion.Visible)
                {
                    str = OngletActive.EditeurTextOnglet.ActiveTextAreaControl.Document.TextContent;
                    bthp = true;
                }
        }

        /// <summary>
        /// Déclache l'événement Closing.
        /// Si il y'a des document ouvert et a été modifié, Alors damande est-ce-que veillez-vous sauvgarder le travaille.
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            ConfirmationEnregistrement = new ConfirmationFrom(OngletsCollection);
            ConfirmationEnregistrement.ShowDialog();
            switch (ConfirmationEnregistrement.DialogResult)
            {
                case DialogResult.Yes:
                    new OngletActions(OngletsCollection).FermerTout(false);
                    break;
                case DialogResult.Cancel:
                    e.Cancel = true;
                    return;
                    break;
            }
            try
            {
                RecentFileMaping.EnregistrerLitseRecentFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            if (ThComp != null)
                try
                {
                    ThComp.Abort();
                }
                catch
                {
                }
            if (Completion != null)
                if (Completion.ThreadParserGrammaire != null)
                    try
                    {
                        Completion.ThreadParserGrammaire.Abort();
                    }
                    catch
                    {
                    }
            if (ThComp != null) ThComp.Abort();
            if (ThCompParant != null) ThCompParant.Abort();


            base.OnFormClosing(e);
            if (startForm != null) startForm.Close();
            Thread.Sleep(500);
            if (formS != null) formS.Show();

        }

        #region Ribbon Diplay

        private void ribbonButtonSolutionExplorer_Click(object sender, EventArgs e)
        {
            solutionExplorer.Démarer();
        }

        private void ribbonButtonVoiceOption_Click(object sender, EventArgs e)
        {
            voiceOption.Démarer();
        }

        private void ribbonButtonFunctionsList_Click(object sender, EventArgs e)
        {
            fonctionsList.Démarer();
        }

        private void ribbonButtonVariablesList_Click(object sender, EventArgs e)
        {
            variablesList.Démarer();
        }

        private void ribbonButtonErrorList_Click(object sender, EventArgs e)
        {
            errorList.Démarer();
        }

        private void ribbonButtonOutput_Click(object sender, EventArgs e)
        {
            output.Démarer();
        }

        private void ribbonButtonSearchResult_Click(object sender, EventArgs e)
        {
            searchResult.Démarer();
        }

        #endregion

        #region Ribbon Laguages

        private void ribbonButtonLanguageZ1_Click(object sender, EventArgs e)
        {
            //LangageActive = Langages.Z1;
        }

        private void ribbonButtonLanguageZ2_Click(object sender, EventArgs e)
        {
            LangageActive = Langages.Z2;
        }

        #endregion

        private FormEditorSimple formEditorSimple;
        private void ribbonButton9_Click(object sender, EventArgs e)
        {
            formEditorSimple.Show();
            formEditorSimple.Activate();
        }

        private void ribbonButton2_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            printPreviewDialog1 = new PrintPreviewDialog();
            printPreviewDialog1.Document = OngletActive.EditeurTextOnglet.PrintDocument;
            printPreviewDialog1.TopMost = true;
            printPreviewDialog1.Owner = this;
            printPreviewDialog1.Show();

        }

        #region Run & Compile

        private Process ProcessBuild;
        private Process ProcessRun;
        public bool SimulatorAll = false;
        public int SimulationPas = 2;

        private void InitProcess()
        {
            try
            {
                ProcessRun.Kill();
            }
            catch
            {
            }
            try
            {
                ProcessBuild.Kill();
            }
            catch
            {
            }
            try
            {
                ProcessIndentation.Kill();
            }
            catch
            {
            }
            ProcessBuild = new Process();
            ProcessRun = new Process();
            ProcessIndentation = new Process();
            ProcessBuild.Exited += ProcessBuild_Exited;
            ProcessRun.Exited += ProcessRun_Exited;
            ProcessIndentation.Exited += ProcessIndentation_Exited;
            File.Delete(@".\Languages\LanguageZ\kwz\fileCompil.txt");
            File.Delete(@".\Languages\LanguageZ\kwz\f_erreur.txt");
            File.Delete(@".\Languages\LanguageZ\kwz\Fcompil.kwz");
            File.Delete(@".\Languages\LanguageZ\kwz\Res.pas");
        }

        void ProcessRun_Exited(object sender, EventArgs e)
        {
        }

        void ProcessBuild_Exited(object sender, EventArgs e)
        {
        }

        private bool boolWatcherBuild = true;
        private void ribbonButtonBuild_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            InitProcess();
            try
            {
                errorList.kryptonDataGridView1.Rows.Clear();
                errorList.HideRapide();
                boolWatcherIndentation = false;
                new ConvertTabsToSpaces().Execute(TextAreaOngletActive);
                TextWriter streamWriter = new StreamWriter(@".\Languages\LanguageZ\kwz\fileCompil.txt", false);
                streamWriter.Write(new ConversionZFrEnu(DocumentOngletActive.TextContent, true).ConverterEnuVersFr());
                streamWriter.Close();
                boolWatcherIndentation = true;

                ProcessBuild.StartInfo.FileName = @".\Languages\LanguageZ\kwz\Compiler.exe";
                ProcessBuild.StartInfo.Arguments = @".\Languages\LanguageZ\kwz\fileCompil.txt";
                ProcessBuild.Start();
            }
            catch (Exception ex)
            {
                boolWatcherIndentation = true;
                InitProcess();
                MessageBox.Show(ex.Message);
            }
        }

        private void ribbonButtonRun_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            InitProcess();
            try
            {
                errorList.kryptonDataGridView1.Rows.Clear();
                errorList.HideRapide();
                boolWatcherIndentation = false;
                new ConvertTabsToSpaces().Execute(TextAreaOngletActive);
                TextWriter streamWriter = new StreamWriter(@".\Languages\LanguageZ\kwz\fileCompil.txt", false);
                streamWriter.Write(new ConversionZFrEnu(DocumentOngletActive.TextContent, true).ConverterEnuVersFr());
                streamWriter.Close();
                boolWatcherIndentation = true;

                ProcessRun.StartInfo.FileName = @".\Languages\LanguageZ\kwz\Executer2.exe";
                ProcessRun.StartInfo.Arguments = @".\Languages\LanguageZ\kwz\fileCompil.txt F F 0";
                ProcessRun.Start();
            }
            catch (Exception ex)
            {
                boolWatcherIndentation = true;
                InitProcess();
                MessageBox.Show(ex.Message);
            }
        }

        private void ribbonButtonSimulator_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            InitProcess();
            try
            {
                errorList.kryptonDataGridView1.Rows.Clear();
                errorList.HideRapide();
                boolWatcherIndentation = false;
                new ConvertTabsToSpaces().Execute(TextAreaOngletActive);
                TextWriter streamWriter = new StreamWriter(@".\Languages\LanguageZ\kwz\fileCompil.txt", false);
                streamWriter.Write(new ConversionZFrEnu(DocumentOngletActive.TextContent, true).ConverterEnuVersFr());
                streamWriter.Close();
                boolWatcherIndentation = true;

                ProcessRun.StartInfo.FileName = @".\Languages\LanguageZ\kwz\Executer.exe";
                ProcessRun.StartInfo.Arguments = @".\Languages\LanguageZ\kwz\fileCompil.txt V " + (SimulatorAll ? "V" : "F") +
                                                 " " + SimulationPas;
                ProcessRun.Start();
            }
            catch (Exception ex)
            {
                boolWatcherIndentation = true;
                InitProcess();
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region indenattion &TC

        private void ProcessIndentation_Exited(object sender, EventArgs e)
        {
        }

        private Process ProcessIndentation;
        public bool IndentatonMajuscule = true;
        public int IndentationPasAeration = 4;

        public void ribbonButtonIndentation_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            InitProcess();
            try
            {
                errorList.kryptonDataGridView1.Rows.Clear();
                boolWatcherIndentation = false;
                const string path = @".\Languages\LanguageZ\kwz\fileCompil.txt";
                new ConvertTabsToSpaces().Execute(TextAreaOngletActive);

                using (FileStream fs = new FileStream(path, FileMode.Create))
                using (TextWriter streamWriter = new StreamWriter(fs))
                    streamWriter.Write(new ConversionZFrEnu(DocumentOngletActive.TextContent, true).ConverterEnuVersFr());
                boolWatcherIndentation = true;

                ProcessIndentation.StartInfo.FileName = @".\Languages\LanguageZ\kwz\Indenter2.exe";
                ProcessIndentation.StartInfo.Arguments = @".\Languages\LanguageZ\kwz\fileCompil.txt " + IndentationPasAeration +
                                                         (IndentatonMajuscule ? " OUI" : " NON");
                ProcessIndentation.StartInfo.UseShellExecute = false;
                ProcessIndentation.Start();
                Thread.Sleep(100);
            }
            catch (Exception ex)
            {
                boolWatcherIndentation = true;
                InitProcess();
                MessageBox.Show(ex.Message);
            }
        }

        private void ribbonButtonMasquerCode_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            try
            {
                string st = TextAreaOngletActive.SelectionManager.SelectedText.Trim();
                if (st.StartsWith("/*") && st.EndsWith("*/") || st.StartsWith("{") && st.EndsWith("}"))
                    return;

                string text = "/*" + TextAreaOngletActive.SelectionManager.SelectedText + "*/";
                TextAreaOngletActive.Document.Replace(
                    TextAreaOngletActive.Document.PositionToOffset(TextAreaOngletActive.SelectionManager.selectionStart),
                    TextAreaOngletActive.SelectionManager.SelectedText.Length, text);

                TextAreaOngletActive.SelectionManager.SetSelection(TextAreaOngletActive.SelectionManager.selectionStart,
                                                                   DocumentOngletActive.OffsetToPosition(
                                                                       DocumentOngletActive.PositionToOffset(
                                                                           TextAreaOngletActive.SelectionManager.selectionStart) +
                                                                       TextAreaOngletActive.SelectionManager.SelectedText.Length + 2));
            }
            catch { }
        }

        private void ribbonButtonDemasquerCode_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            string st = TextAreaOngletActive.SelectionManager.SelectedText;
            if (!st.Trim().StartsWith("/*") || !st.Trim().EndsWith("*/")) return;
            string text = st.Trim().Substring(2, st.Trim().Length - 4);
            TextAreaOngletActive.Document.Replace(
                TextAreaOngletActive.Document.PositionToOffset(TextAreaOngletActive.SelectionManager.selectionStart),
                st.Length, text);
            MoveToEndLine();
        }

        private void ribbonButtonDeplacerD_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;

            int index = TextAreaOngletActive.Document.PositionToOffset(TextAreaOngletActive.SelectionManager.selectionStart);
            DocumentOngletActive.Insert(index, "    ");
            int index2 = index + TextAreaOngletActive.SelectionManager.SelectedText.Length;
            while (index < index2)
            {
                index = DocumentOngletActive.TextContent.IndexOf("\r\n", index, index2 - index);
                if (index < 0) break;
                DocumentOngletActive.Insert(index + 4, "    ");
                index += 4;
                index2 += 4;
                TextAreaOngletActive.Document.UndoStack.Pop();
            }
            TextAreaOngletActive.SelectionManager.SetSelection(TextAreaOngletActive.SelectionManager.selectionStart,
                                                               DocumentOngletActive.OffsetToPosition(index2));
            MoveToEndLine();
        }

        private void ribbonButtonDeplacerG_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;

        }

        #endregion

        private bool boolWatcherIndentation = true;
        private ListeErrorZ listeErrorZ = new ListeErrorZ();
        private void fileSystemWatcherIndentation_Changed(object sender, FileSystemEventArgs e)
        {
            if (Path.GetFileName(e.FullPath).ToLower() != "fcompil.kwz") return;
            errorList.kryptonDataGridView1.Rows.Clear();
            errorList.HideRapide();
            StreamReader streamReader2 = null;
            StreamReader streamReader3 = null;
            {
                try
                {
                    streamReader2 = new StreamReader(@".\Languages\LanguageZ\kwz\Fcompil.kwz");
                    string[] tabstr = streamReader2.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    streamReader2.Close();
                    string s2 = tabstr[tabstr.Length - 2].Replace("�", "é");
                    if (s2.Trim().StartsWith(">>>"))
                    {
                        string posColon = tabstr[tabstr.Length - 3].IndexOf("").ToString();
                        string posLigne = tabstr[tabstr.Length - 4].Substring(0, tabstr[tabstr.Length - 4].IndexOf(" "));
                        string findError = listeErrorZ.FindError(s2.Substring(s2.IndexOf(":")+1));
                        errorList.kryptonDataGridView1.Rows.Add(findError, int.Parse(posLigne), int.Parse(posColon) - posLigne.Length);
                        errorList.ShowRapide();
                    }
                    else
                    {
                        streamReader3 = File.Exists(@".\Languages\LanguageZ\kwz\Rep.pas")
                                            ? new StreamReader(@".\Languages\LanguageZ\kwz\Rep.pas")
                                            : new StreamReader(@".\Languages\LanguageZ\kwz\fileCompil.txt");
                        string s = new ConversionZFrEnu(streamReader3.ReadToEnd(), true).ConverterFrVersEnu();
                        streamReader3.Close();
                        DocumentOngletActive.TextContent = s;
                    }
                }
                catch (Exception ex)
                {
                    if (streamReader2 != null) streamReader2.Close();
                    if (streamReader3 != null) streamReader3.Close();
                    //MessageBox.Show(ex.Message);
                }
            }
        }

        private void fileSystemWatcherExecuter_Changed(object sender, FileSystemEventArgs e)
        {
            if (!boolWatcherIndentation) return;
            if (Path.GetFileName(e.FullPath).ToLower() == "resultats.kwz")
            {
                StreamReader streamReader = new StreamReader(@".\Languages\LanguageZ\kwz\resultats.kwz");
                string s = streamReader.ReadToEnd();
                streamReader.Close();
                output.editeurTextOutput.Document.TextContent = s;
            }
        }

        void errorList_gridViewCellMouseEventHandler(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                int posLigne = int.Parse(errorList.kryptonDataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString()) - 1;
                int posColon = int.Parse(errorList.kryptonDataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString()) - 1;

                TextAreaOngletActive.Caret.Position = new Point(posColon, posLigne);
                TextAreaOngletActive.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ribbonButtonOptionIndentation_Click(object sender, EventArgs e)
        {
            OptionsIndentation optionsIndentation = new OptionsIndentation(this);
            optionsIndentation.ShowDialog();
        }

        private void ribbonButtonOptionRun_Click(object sender, EventArgs e)
        {
            OptionsSimulation optionsSimulation = new OptionsSimulation(this);
            optionsSimulation.ShowDialog();
        }

        private void ribbonButtonHelpeZ_Click(object sender, EventArgs e)
        {
            Process.Start(@".\Languages\LanguageZ\kwz\editeur\aide_langz.HLP", "1003");
        }

        private void ribbonButtonReport_Click(object sender, EventArgs e)
        {
            Exposé exposé = new Exposé();
            exposé.Show();
        }

        private void ribbonButtonZToC_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            ZToC zToC = new ZToC(DocumentOngletActive.TextContent);
            zToC.Show();
        }

        private void ribbonButtonZToPascal_Click(object sender, EventArgs e)
        {
            if (OngletActive == null) return;
            ZToPascal zToPascal = new ZToPascal(DocumentOngletActive.TextContent);
            zToPascal.Show();
        }
    }
}